package corewarsxxi.logic;

import java.io.Serializable;

/**
 * Instruction <code>add</code> from Core Wars.
 * <p>Contains a static self to be used by all instances of MemoryCell.</p>
 * @version ICWS 88
 * @see     corewarsxxi.logic.OpCode
 * @author  Luís Fonseca, ei10139 @ FEUP
 */
public class add extends OpCode implements Serializable
{
    /** Core the instance.*/
    private transient Core c = super.getCore();
    
    /** Simplefied Singleton that provides access to a final static <code>add</code> instance.*/
    public static final add self = new add();

    /**
     * Private constructor of add.
     */
    private add() {}

    public void operation(MemoryField aField, MemoryField bField)
    {
        if(AMImmediate.self.equals(aField.aMode))
        {
            if(AMImmediate.self.equals(bField.aMode))
            {
                MemoryCell mc = c.memArray.get(c.currentWarrior.processes.peek().offset);
                mc.setStoredbFieldValue(aField.getValue() + bField.getValue());
                return;
            }
            MemoryCell mc = c.memArray.get(bField.getValue());
            mc.setStoredbFieldValue(mc.bField.value + aField.getValue());
            return;
        }
        if(AMImmediate.self.equals(bField.aMode))
        {
            MemoryCell mc = c.memArray.get(aField.getValue());
            int valB = mc.bField.getStoredValue();
            mc = c.memArray.get(c.currentWarrior.processes.peek().offset);
            mc.setStoredbFieldValue(mc.bField.value + valB);
            return;
        }
        MemoryCell mc = c.memArray.get(aField.getValue());
        int valA = mc.aField.getStoredValue();
        int valB = mc.bField.getStoredValue();
        mc = c.memArray.get(bField.getValue());
        //mc.aField.setStoredValue(mc.aField.value + valA);
        //mc.bField.setStoredValue(mc.bField.value + valB);
        mc.setStoredaFieldValue(mc.aField.value + valA);
        mc.setStoredbFieldValue(mc.bField.value + valB);
    }

    /**
     * Makes use of the Singleton pattern and returns the public static object.
     * @return it<i>self</i>.
     */
    public OpCode getSelf()
    {
        return add.self;
    }

    /**
     * Overrides the default Object.toString() function.
     * @return Always returns "<code>add</code>".
     */
    @Override
    public String toString()
    {
        return "add";
    }
}
